package com.fujimana.rockincat.restree.phase;

import java.util.Locale;
import java.util.Map;

import com.fujimana.rockincat.restree.converter.Converter;
import com.fujimana.rockincat.restree.exception.HttpException;
import com.fujimana.rockincat.restree.init.Init;
import com.fujimana.rockincat.restree.util.HttpUtils.HttpStatusCode;

public class BindResponseValuePhase implements Phase {

	@Override
	public void execute(Map<String, Object> context) {
		Init init = (Init) context.get(Init.class.getName());
		Converter converter = init.getResponseConverter((String) context
				.get("contentType"));

		Locale locale = (Locale) context.get("locale");
		String charset = (String) context.get("charset");

		if (converter == null) {
			throw new HttpException(HttpStatusCode.BAD_REQUEST);
		}

		Object ret = context.get("return");
		context.remove("return");
		
		if(ret != null) {
			byte[] b = converter.format(ret, locale, charset);

			if (b == null) {
				throw new HttpException(HttpStatusCode.INTERNAL_SERVER_ERROR);
			}
			
			context.put("return", b);
		}

	}

	@Override
	public String getId() {
		return BindResponseValuePhase.class.getSimpleName();
	}

	@Override
	public boolean isChain() {
		return true;
	}
}
